package com.nowcoder.community.service;

import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginTicketMapper loginTicketMapper;
    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    public User findUserById(int id) {
//        return userMapper.selectById(id);
        User user = getCache(id);
        if (user==null){
            user=initCache(id);
        }
        return user;
    }

    /**
     * 注册账号
     * @author ProgramCat
     * @param user 用户信息
     * @return Map<Object>  结果
     */
    public Map<String,Object> register(User user){
        HashMap<String, Object> map = new HashMap<>();

        if(user==null){
            //错误传参
            throw new IllegalArgumentException("参数为空");
        }
        //StringUtils.isBlank(参数) 能判断参数是否为null,"",是则false
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }

        // 验证账号
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        // 验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已被注册!");
            return map;
        }
        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));//设置盐，取uuid前五位
        user.setPassword(CommunityUtil.md5(user.getPassword()+user.getSalt()));//取出上面设置的盐加密，注意括号位置
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));//通过%d占位符替换
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        //激活邮箱
        Context context = new Context(); //参考：https://blog.csdn.net/ychyssss/article/details/50326743
        context.setVariable("email", user.getEmail());
        //拼接邮箱：http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);//参数为：（设置对应模板对象路径，渲染参数）
        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }
    /**
     * 邮箱激活
     * @author ProgramCat
     * @param userId 用户id
     * @param code 激活码
     * @return int
     */
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }
    /**
     * 账号登录
     * @author ProgramCat
     * @param username 用户名
     * @param password 密码
     * @param expiredSeconds 记住我（按钮值）
     * @return Map<Object>
     */
    public Map<String,Object> login(String username,String password,int expiredSeconds){
        HashMap<String, Object> map = new HashMap<>();

        //传参为空
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        // 验证账号
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }
        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }
        // 验证密码
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }
        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID()); //登录凭证码
        loginTicket.setStatus(0);//0为登录
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));//设置失效时间
//        loginTicketMapper.insertLoginTicket(loginTicket);
        /*将凭证放到Redis中*/
        String redisKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey,loginTicket);

        map.put("ticket", loginTicket.getTicket());
        return map;
    }
    /**
     * 退出登录
     * @author ProgramCat
     * @param ticket 状态码
     */
    public void logout(String ticket) {
//        loginTicketMapper.updateStatus(ticket, 1);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey, loginTicket);
    }
    /**
     * 查询当前是否登录
     * @author ProgramCat
     * @param ticket 状态码
     * @return LoginTicket
     */
    public LoginTicket findLoginTicket(String ticket) {
//        return loginTicketMapper.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 修改头像地址
     * @author ProgramCat
     * @date 2023/4/1 11:33
     * @param userId 用户id
     * @param headerUrl  头像地址
     * @return int
     */
    public int updateHeader(int userId, String headerUrl) {
//        return userMapper.updateHeader(userId, headerUrl);
        int rows =userMapper.updateHeader(userId, headerUrl);
        clearCache(userId);
        return rows;
    }


    /**
     * 修改密码
     * @author ProgramCat
     * @date 2023/4/1 11:34
     * @param oldPassword 旧密码
     * @param nowPassword 新密码
     * @return HashMap<Object> 结果
     */
    public HashMap<String, Object> updatePassword(String oldPassword,String nowPassword){
        HashMap<String, Object> map = new HashMap<>();

        if (StringUtils.isBlank(oldPassword)&&StringUtils.isBlank(nowPassword)){
            map.put("oldPasswordMsg", "旧密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(nowPassword)){
            map.put("nowPasswordMsg", "新密码不能为空!");
            return map;
        }

        User user = hostHolder.getUser();
        oldPassword=CommunityUtil.md5(oldPassword+user.getSalt());
        nowPassword=CommunityUtil.md5(nowPassword+user.getSalt());
        if (!oldPassword.equals(user.getPassword())){
            map.put("oldPasswordMsg", "原密码输入有误");
            return map;
        }
        if (oldPassword.equals(nowPassword)){
            map.put("oldPasswordMsg", "原密码和新密码相同");
            return map;
        }

        /**
         * 修改密码
         * @author ProgramCat
         * @param oldPassword 旧密码
         * @param nowPassword 新密码
         * @return HashMap<Object>
         */
         if(userMapper.updatePassword(user.getId(), nowPassword)==1){
             map.put("success",true);
         }
        return map;
    }
    /**
     * 通过名字查询用户信息
     * @author ProgramCat
     * @date 2023/4/7 17:34
     * @param username 用户名
     * @return User
     */
    public User findUserByName(String username){
        return userMapper.selectByName(username);
    }

    /**
     * 从Redis缓存中先取值
     * @author ProgramCat
     * @date 2023/4/7 17:36
     * @param userId 用户id
     * @return User
     */
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    /**
     * 先从缓存中取值，无法取到初始化缓存数据
     * @author ProgramCat
     * @date 2023/4/7 17:37
     * @param userId 用户id
     * @return User
     */
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    /** 
     * 数据变更时清除缓存数据
     * @author ProgramCat
     * @date 2023/4/7 17:38
     * @param userId 用户id
     */
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }


}
